<template>
  <div class="update-photo">
    <img class="image" :src="image" ref="image" />
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    ></van-nav-bar>
  </div>
</template>

<script>
import { updateUserPhoto } from "@/api/user";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
export default {
  // 组件名称
  name: "UpdatePhoto",
  // 组件参数 接收来自父组件的数据
  props: {
    file: {
      required: true,
    },
  },
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null, //裁切器实例
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {},
  mounted() {
    const image = this.$refs.image;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
  // 组件方法
  methods: {
    getCroppedCanvas() {
      return new Promise((resolve) => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file);
        });
      });
    },
    async onConfirm() {
      this.$toast.loading({
        message: "保存中",
        forbidClick: true, //禁止背景点击
        duration: 0, //展示时间，0表示持续展示
      });

      const file = await this.getCroppedCanvas();
      const fd = new FormData();
      fd.append("photo", this.file);

      /* 如果Content-Type为multipart/form-data，必须提交FormData数据对象，专门用于文件上传的，不能提交{}，类型不匹配 */
      /* const fd = new FormData();
      fd.append("photo", this.file); */
      await updateUserPhoto(fd);

      this.$toast.success("保存成功");
      //更新父组件
      this.$emit("update-photo", window.URL.createObjectURL(file));
      //关闭弹出层
      this.$emit("close");
    },
  },
};
</script> 

<style scoped lang='less'>
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
.image {
  /* Ensure the size of the image fit the container perfectly */
  img {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
  }
}
</style>
